package com.sportmall.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * 读取项目配置参数
 * 使用静态构造函数在第一次访问时初始化Properties对象
 */
public class PropertiesUtil {
    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    private static Properties properties;

    static {
        String filename = "project.properties";
        properties = new Properties();
        try {
            properties.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(filename), "UTF-8"));
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 读取配置
     * @param key 键
     * @return
     */
    public static String getProperty(String key) {
        String value = properties.getProperty(key);
        return StringUtils.isBlank(value) ? null : value.trim();
    }

    /**
     * 读取配置
     * @param key 键
     * @param defaultValue 默认值
     * @return
     */
    public static String getProperty(String key, String defaultValue){
        String value = properties.getProperty(key);
        return StringUtils.isBlank(value) ? defaultValue : value.trim();
    }
}
